#include "ThreadPool.h"
namespace re
{
	namespace core
	{
		void ThreadPool::AllocateThreads(ManagerContainer* managers)
		{
			for(int i = 0; i < 4; ++i)
			{
				std::thread thr;
				Thread* thread = new Thread();
				threads_.push_back(ThreadPtr(thread));
				thread->LaunchThread(managers->task_manager);
			}
		}
		void ThreadPool::Release(ITaskManager* tasks)
		{
			for( int i = 0; i < threads_.size(); ++i)
			{
				threads_[i]->finish = true;
			}
			SessionId sid = tasks->StartSession();
			TaskId parent = tasks->AddTask(WorkPtr(new DoNothingWork()), sid);
			for( int i = 0; i < threads_.size() - 1; ++i)
			{
				TaskId child = tasks->AddTask(WorkPtr(new DoNothingWork()), sid);
				tasks->SetParent(sid, parent, child);
			}
			tasks->FinishSession(sid);
			for(int i = 0; i < threads_.size(); ++i)
			{
				threads_[i]->thread_.join();
			}
			threads_.clear();
		}
		void Thread::Run(Thread* thread, ITaskManager* feed)
		{
			thread->MainLoop(feed);
		}
		void Thread::LaunchThread(ITaskManager* feed)
		{
			thread_ = std::thread(Thread::Run, this, feed);
		}
		void Thread::MainLoop(ITaskManager* feed)
		{
			while(!finish)
			{
				feed->WaitDoTask();
			}
		}
	}
}